<template>
    <Page>
        <div class="wx-chat-container">
            <!-- 聊天内容区域 -->
            <div
                class="wx-chat-content"
                :style="type === 1 ? 'height:calc(100vh - 200px)' : 'min-height: 500px; max-height: 500px;'"
                ref="chatContentRef"
            >
                <!-- 无消息提示 -->
                <div v-if="chatData.length === 0" class="no-messages">暂无聊天记录</div>
                <!-- 聊天消息列表 -->
                <div v-else class="message-list">
                    <!-- 消息项 -->
                    <div
                        v-for="(message, index) in chatData"
                        :key="index"
                        :class="[
                            'message-item',
                            !message.messageSource ? 'self-message' : 'other-message'
                        ]"
                    >
                        <!-- 消息时间 -->
                        <div class="message-time">{{ message.createTime }}</div>
                        <!-- 发送方头像 -->
                        <div v-if="message.messageSource" class="avatar">
                            <img
                                v-if="message.formAvatarUrl"
                                :src="message.formAvatarUrl"
                                alt="头像"
                            />
                            <div v-else class="avatar-placeholder">
                                {{ message.formUsername?.charAt(0) || '?' }}
                            </div>
                        </div>

                        <!-- 消息内容 -->
                        <div class="message-content">
                            <!-- 发送方名称 -->
                            <div v-if="message.messageSource" class="sender-name">
                                {{ message.formUsername || '对方' }}
                            </div>
                            <div v-else class="sender-name2">{{ message.username || '我' }}</div>

                            <!-- 消息气泡 -->
                            <div
                                :class="[
                                    'message-bubble',
                                    !message.messageSource ? 'self-bubble' : 'other-bubble'
                                ]"
                            >
                                <!-- 文本消息 -->
                                <div class="text-message">
                                    {{ message.messageText }}
                                </div>
                            </div>
                        </div>

                        <!-- 自己的头像 -->
                        <div v-if="!message.messageSource" class="avatar">
                            <img v-if="props.avatarUrl" :src="props.avatarUrl" alt="头像" />
                            <div v-else class="avatar-placeholder">
                                {{ userInfo.name?.charAt(0) || '我' }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 聊天输入框区域 -->
            <Spin :spinning="loading">
                <div class="wx-chat-input-area">
                    <div class="input-container">
                        <textarea
                            v-model="inputValue"
                            class="chat-input"
                            placeholder="请输入消息..."
                            rows="1"
                            @keydown.enter.prevent="handleEnterKey"
                            @input="autoResizeTextarea"
                        ></textarea>
                    </div>
                    <button class="send-btn" @click="sendMessage" :disabled="!inputValue.trim()">
                        发送
                    </button>
                </div>
            </Spin>
        </div>
    </Page>
</template>

<script setup lang="ts">
import {
    ref,
    onMounted,
    onUpdated,
    watch,
    defineProps,
    withDefaults,
    onUnmounted,
    onBeforeUnmount
} from 'vue'
import type { Ref } from 'vue'
import { PageApi } from '../use/api'
import { Spin } from 'ant-design-vue'
var timer = ref<any>(null)
// 定义用户信息接口
interface UserInfo {
    name?: string
    avatar?: string
}

// 定义组件 props
const props = withDefaults(
    defineProps<{
        userInfo?: UserInfo
        chatInfo?: any
        avatarUrl?: string
        type?: number
        open?: boolean
    }>(),
    {
        userInfo: () => ({})
    }
)
const type = ref(props.type)
// 聊天内容区域引用
const chatContentRef: Ref<HTMLDivElement | null> = ref(null)
// 输入框内容
const inputValue: Ref<string> = ref('')
// 文本区域引用
const textareaRef: Ref<HTMLTextAreaElement | null> = ref(null)

// 滚动到底部
const scrollToBottom = () => {
    if (chatContentRef.value) {
        chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
}
// 获取聊天记录
const chatData: any = ref([])
const getChatList = async () => {
    const res = await PageApi.getChatList({
        username: props.chatInfo.username,
        formUserId: props.chatInfo.formUserId
    })
    if (res) {
        chatData.value = res.length > 0 ? res.reverse() : []
    }
    // 轮询
    timer.value = setInterval(async () => {
        const res = await PageApi.getChatList({
            username: props.chatInfo.username,
            formUserId: props.chatInfo.formUserId
        })
        if (res) {
            chatData.value = res.length > 0 ? res.reverse() : []
        }
    }, 5000)
}
// 获取聊天记录
getChatList()

// 发送消息
const loading = ref<boolean>(false)
const sendMessage = async () => {
    const content = inputValue.value.trim()
    if (!content) return
    loading.value = true
    const res = await PageApi.send({
        targetUserId: props.chatInfo.formUserId,
        messageText: content,
        monitorId: props.chatInfo?.monitorId
    })
    console.log(res)
    loading.value = false
    // 清空输入框
    inputValue.value = ''
    // 重置文本框高度
    if (textareaRef.value) {
        textareaRef.value.style.height = 'auto'
    }

    // 滚动到底部
    setTimeout(() => {
        scrollToBottom()
    }, 100)
}

// 处理回车键
const handleEnterKey = (event: KeyboardEvent) => {
    // 如果按下的是Enter键且没有按下Shift键
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault()
        sendMessage()
    }
}

// 自动调整文本框高度
const autoResizeTextarea = () => {
    const textarea = document.querySelector('.chat-input') as HTMLTextAreaElement
    if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = textarea.scrollHeight + 'px'
        // 限制最大高度
        if (textarea.scrollHeight > 120) {
            textarea.style.height = '120px'
            textarea.style.overflowY = 'auto'
        } else {
            textarea.style.overflowY = 'hidden'
        }
    }
}

// 监听聊天消息变化，自动滚动到底部
watch(
    () => chatData.value,
    () => {
        scrollToBottom()
    },
    { deep: true }
)
watch(
    () => props.open,
    (newVal) => {
        if (!newVal) {
            if (timer.value) {
                clearInterval(timer.value)
                timer.value = null
            }
        }
    }
)
// 在组件卸载时清除定时器
onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})
// 在组件卸载前清除定时器
onBeforeUnmount(() => {
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})
// 组件挂载和更新时滚动到底部
onMounted(() => {
    scrollToBottom()
})

onUpdated(() => {
    scrollToBottom()
})
</script>

<style scoped lang="scss">
.wx-chat-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
    border-radius: 8px;
    overflow: hidden;
}

.wx-chat-header {
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.chat-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.wx-chat-content {
    overflow-y: auto;
    padding: 20px;
    scrollbar-width: thin;
    scrollbar-color: #d9d9d9 #f0f0f0;

    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: #f0f0f0;
        border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
        background: #d9d9d9;
        border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb:hover {
        background: #bfbfbf;
    }
}

.no-messages {
    text-align: center;
    color: #999;
    padding: 40px 0;
    font-size: 14px;
}

.message-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.message-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    position: relative;

    &.self-message {
        justify-content: flex-end;
    }

    &.other-message {
        justify-content: flex-start;
    }
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .avatar-placeholder {
        width: 100%;
        height: 100%;
        background-color: #e6f7ff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        font-weight: 600;
        color: #1890ff;
    }
}

.message-content {
    max-width: 60%;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.sender-name {
    font-size: 12px;
    color: #999;
    padding-left: 8px;
}
.sender-name2 {
    font-size: 12px;
    color: #999;
    text-align: right;
}
.message-bubble {
    padding: 10px 14px;
    border-radius: 12px;
    word-wrap: break-word;
    word-break: break-word;

    &.self-bubble {
        background-color: #95ec69;
        border-bottom-right-radius: 4px;
    }

    &.other-bubble {
        background-color: #fff;
        border-bottom-left-radius: 4px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
}

.text-message {
    font-size: 14px;
    line-height: 1.5;
    color: #333;
}

.image-message {
    max-width: 200px;

    img {
        width: 100%;
        border-radius: 8px;
        cursor: pointer;
        transition: transform 0.2s;

        &:hover {
            transform: scale(1.02);
        }
    }
}

.file-message {
    a {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #1890ff;
        text-decoration: none;

        &:hover {
            text-decoration: underline;
        }

        .file-icon {
            width: 20px;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 4px;
            display: inline-block;
        }

        .file-size {
            font-size: 12px;
            color: #999;
        }
    }
}

.voice-message {
    .play-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        background: none;
        border: none;
        cursor: pointer;
        color: #333;

        &:hover {
            color: #1890ff;
        }

        .play-icon {
            width: 16px;
            height: 16px;
            background-color: rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            display: inline-block;
        }
    }
}

.message-time {
    font-size: 11px;
    color: #999;
    position: absolute;
    bottom: -20px;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
}

/* 聊天输入框区域样式 */
.wx-chat-input-area {
    background-color: #fff;
    border-top: 1px solid #e5e5e5;
    padding: 12px 20px;
    display: flex;
    align-items: flex-end;
    gap: 12px;
}

.input-container {
    flex: 1;
    position: relative;
    min-height: 40px;
}

.chat-input {
    width: 100%;
    min-height: 40px;
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 20px;
    resize: none;
    font-size: 14px;
    line-height: 1.4;
    outline: none;
    transition: border-color 0.3s;
    background-color: #f5f5f5;
    color: #000;
    &:focus {
        border-color: #1890ff;
        background-color: #fff;
    }

    &::placeholder {
        color: #999;
    }
}

.send-btn {
    width: 64px;
    height: 40px;
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    flex-shrink: 0;

    &:hover:not(:disabled) {
        background-color: #40a9ff;
    }

    &:disabled {
        background-color: #d9d9d9;
        cursor: not-allowed;
        color: #bfbfbf;
    }
}
</style>
